from time import sleep

from data_structures.coord import Coord
import matplotlib.pyplot as plt


# 返回两个坐标间的欧氏距离
def distance(coord, k_coord):
    d = pow((coord.x - k_coord.x) ** 2 + (coord.y - k_coord.y) ** 2, 0.5)
    return round(d, 5)


# 返回距离最小的簇中心label
def get_label(coord, k1, k2, k3):
    d1 = distance(coord, k1)
    d2 = distance(coord, k2)
    d3 = distance(coord, k3)

    d_set = [d1, d2, d3]
    l = 0

    match d_set.index(min(d_set)):
        case 0:
            l = 0
        case 1:
            l = 1
        case 2:
            l = 2
    return l


# 对簇中心进行坐标化
def show_k(k):
    res = []
    for i in k:
        res.append((i.x, i.y))
    return res


# 结果坐标化
def show_res(res):
    result = [[], [], []]

    for i in res:
        if i:
            for j in i:
                result[j.label].append((j.x, j.y))

    return result


# 返回新的簇中心
def get_new_k(res):
    new_res = []

    for i in res:
        if i:
            sum_x = 0
            sum_y = 0
            for j in i:
                sum_x += j.x
                sum_y += j.y

            new_x = sum_x / len(i)
            new_y = sum_y / len(i)
            new_res.append(Coord(new_x, new_y))

    return new_res


# 显示散点图
def platform(res, k):
    res_x = []
    res_y = []

    k_x = []
    k_y = []

    for i in res:
        if i:
            for j in i:
                res_x.append(j.x)
                res_y.append(j.y)

    for i in k:
        k_x.append(i.x)
        k_y.append(i.y)

    # 绘制散点图
    plt.scatter(x=res_x, y=res_y, c='blue')
    plt.scatter(x=k_x, y=k_y, c='red')

    plt.rcParams["font.sans-serif"] = ["SimHei"]

    # 添加标题和标签
    plt.title('聚类结果散点图')
    plt.xlabel('X')
    plt.ylabel('Y')

    # 显示图形
    plt.show()
    sleep(1)
    plt.close()
